#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QFileDialog>


bool showDebug = true;
bool showTime = true;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    model = new QStringListModel();
    lianxiang = new QStringListModel();

    // 创建QCompleter
    completer = new QCompleter(lianxiang, ui->widgetC);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setCompletionMode(QCompleter::PopupCompletion);

    // 将QCompleter与QLineEdit关联
    ui->le_seams->setCompleter(completer);

    ui->tb_search->setIcon(QApplication::style()->standardIcon(QStyle::SP_ArrowRight));
    this->setWindowTitle("SPD-Log View V1.0");

    textBrowser = new CodeEditor;
    QFont font3;
    font3.setPixelSize(16);
    textBrowser->setFont(font3);
    ui->stackedWidget->addWidget(textBrowser);

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::displayLogsFromZip(const QString& zipFilePath) {
    // 打开zip文件
    zip* zipFile = zip_open(zipFilePath.toUtf8().constData(), ZIP_RDONLY, nullptr);
    if (zipFile == nullptr) {
        spdlog::error("Failed to open zip file.");
        return;
    }

    // 遍历zip文件中的所有条目
    int numEntries = zip_get_num_entries(zipFile, 0);
    for (int i = 0; i < numEntries; ++i) {
        // 获取条目的名称
        const char* logFileName = zip_get_name(zipFile, i, 0);
        if (logFileName == nullptr) {
            spdlog::error("Failed to get file name from zip.");
            continue;
        }

        // 打开日志文件
        zip_file* zfile = zip_fopen_index(zipFile, i, 0);
        if (zfile == nullptr) {
            spdlog::error("Failed to open file in zip: {}", logFileName);
            continue;
        }

        // 读取日志文件内容
        char buffer[1024];
        zip_int64_t bytes_read;
        QByteArray logContent;
        while ((bytes_read = zip_fread(zfile, buffer, sizeof(buffer))) > 0) {
            logContent.append(buffer, bytes_read);
        }

        // 关闭文件
        zip_fclose(zfile);

        LogBuffer[logFileName] = logContent;

    }

    // 关闭zip文件
    zip_close(zipFile);
}

void MainWindow::SetListVIew()
{
    QList<QString> keys;
    for (auto it = LogBuffer.begin(); it != LogBuffer.end(); ++it) {
        keys.append(it.key());
    }

    model->setStringList(keys);
    ui->listView->setModel(model);
}

void MainWindow::GetSeams()
{
    KeyTID.clear();
    QStringList lll;
    for(auto it = LogBuffer.begin();it!=LogBuffer.end();it++){
        // 使用QString::split()按行分割QByteArray
        QStringList lines = QString((it.value())).split('\n', Qt::SkipEmptyParts);
        QByteArray seamLine;

        for (int i = 0; i < qMin(lines.size(), 10); ++i) {
            QByteArray currentLine = lines.at(i).toLocal8Bit();
            if (currentLine.contains("##")) {
                // 使用正则表达式匹配"==>"和"<=="之间的任意文本
                // QRegularExpression regex("##(.*?)##");
                QRegularExpression regex("##(.+?)##");

                QRegularExpressionMatch match = regex.match(currentLine);

                if (match.hasMatch()) {
                    QString name = match.captured(1); // 提取匹配的部分
                    KeyTID[name] = it.key();
                    lll.append(name);
                }
                break; // 找到后即退出循环
            }
        }
    }
    lianxiang->setStringList(lll);
}




void MainWindow::displayLogsInTextBrowser(QPlainTextEdit* textBrowser, const QByteArray& logData) {
    // 假设日志格式为：[时间戳][level]消息
    QString logStr(logData);
    //QRegularExpression regex("\\[(\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\]\\[(info|warn|error)\\]\\: (.*)");
    QRegularExpression regex("\\[(\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?)\\]\\[(info|warn|error|debug)\\]\\: (?:\\[(suc|fail)\\])?(.*)");
    QRegularExpressionMatchIterator matchIterator = regex.globalMatch(logStr);

    while (matchIterator.hasNext()) {
        QRegularExpressionMatch match = matchIterator.next();
        QString timestamp = match.captured(1);
        QString level = match.captured(2);
        QString prefix = match.captured(3); // [suc] 或 [fail] 或 空
        QString message = match.captured(4).trimmed();
        if(message.isEmpty()){
            message = prefix.trimmed();
        }else{
        }

        // 根据日志级别设置颜色
        QString color;
        if (level == "info") {
            color = "black";
        } else if (level == "warn") {
            color = "dark yellow";
        } else if (level == "error") {
            color = "red";
        }else if (level == "debug") {
            color = "rgb(72, 118, 255)"; // 蓝色
            if(!showDebug){
                continue;
            }
        } else {
            color = "black";
        }

        // 根据日志前缀设置颜色
        if (prefix == "suc") {
            color = "green"; // 成功
        } else if (prefix == "fail") {
            color = "red"; // 失败
        } else {

        }
        if(showTime){
            timestamp = '['+timestamp+']';
        }else{
            timestamp = "";
        }

        // 使用HTML标签设置文本颜色并添加到QTextBrowser
        QString logEntry = QString("<span style=\"color: %1;\">%2 %3</span><br/>")
                           .arg(color)
                           .arg(timestamp)
                           .arg(message);
        textBrowser->appendHtml(logEntry);

    }
}

void MainWindow::on_pb_OpenZip_clicked()
{
    auto fileName = QFileDialog::getOpenFileName(this,
          tr("Open Zip"), "logs/zip", tr("Zip Files (*.zip)"));
    LogBuffer.clear();
    KeyTID.clear();
    displayLogsFromZip(fileName);
    SetListVIew();
    GetSeams();
}

void MainWindow::on_listView_activated(const QModelIndex &index)
{
    textBrowser->clear();
    QString selectedKey = index.data().toString();
    currentDisBuffer = LogBuffer.value(selectedKey);
    // 显示在QTextBrowser中
    MainWindow::displayLogsInTextBrowser(textBrowser,currentDisBuffer);
    // textBrowser->setPlainText(value);
}

void MainWindow::on_pb_compress_clicked()
{
    QByteArray Nw;
    for(auto it = LogBuffer.begin();it!=LogBuffer.end();it++){
        Nw.push_back((*it));
        Nw.push_back("\n\n");
    }
    LogBuffer["ALL"] = Nw;
    SetListVIew();
}



void MainWindow::on_pb_showDebug_clicked(bool checked)
{
    textBrowser->clear();
    // QByteArray plt = textBrowser->toPlainText().toUtf8();
    showDebug = checked;
    MainWindow::displayLogsInTextBrowser(textBrowser,currentDisBuffer);
}

void MainWindow::on_tb_search_clicked()
{
    auto dd = ui->le_seams->text();
    auto list = model->stringList();
    int xx =list.indexOf(KeyTID[dd]);
    ui->listView->setCurrentIndex(model->index(xx,0));
    on_listView_activated(model->index(xx,0));
}

void MainWindow::on_pb_showTime_clicked(bool checked)
{
    textBrowser->clear();
    showTime = checked;
    MainWindow::displayLogsInTextBrowser(textBrowser,currentDisBuffer);
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_F) {
        // 调用QTextBrowser的查找功能
        // 假设你已经有了一个名为textBrowser的QTextBrowser实例
        QString selectedText = textBrowser->textCursor().selectedText();
        textBrowser->find(selectedText);
        ui->le_seams->setText(selectedText);
    } else {
        QMainWindow::keyPressEvent(event); // 调用基类的处理方法
    }

}
